import os, string
from tagger import *

def CreateFolder(path):
	error = False
	if not os.path.exists(path):
			try:
				os.makedirs(path)
			except OSError:
				print "Error: could not create the folder", path
				error = True
	return error

def Capitalize(string):
	"""Splits by whitespaces, captitalizes every substring and returns it
		as one string"""
	if (string == None ) or len(string) == 0: return None

	string = string.replace('_', ' ')
	string = string.strip()
	sl = string.split(' ')
	for i in range(len(sl)):
		sl[i] = sl[i].capitalize()

	res = ''								#build the resulting string
	for i in range(len(sl)):
		if (sl[i] != '') and (sl[i] != ' '):
			res = res + ' ' + sl[i]

	if len(res) == 0: return None;

	if (res[0] == ' ') and len(res)> 1:
		res = res[1:]

	return res

def Title(string):

	#string = string.title()	 # has some porblems with umlauts
	string = Capitalize(string)
	if string  == None: return None
	string = string.replace('_', ' ')
	string = string.strip()

	sl = string.split(' ')					# Remove double whitespaces
	res = ''								# in the middle of the string
	for i in range(len(sl)):
		if (sl[i] != '') and (sl[i] != ' '):
			res = res + ' ' + sl[i]

	if len(res) == 0: return None;

	if (res[0] == ' ') and len(res)> 1:
		res = res[1:]

	return res

def GetArtAlbv1(id3, song):
	"""Searches for artist and album of a given song from v1-Tag"""

	alb = id3.album.decode('iso-8859-1')
	art = id3.artist.decode('iso-8859-1')
	trk = id3.track

	return alb, art, trk

def GetArtAlbv2(id3, song):
	"""Searches for artist and album of a given song from v2-Tag"""
	alb = None
	art = None
	trk = None

	#message_done = False
	for frame in id3.frames:
		t = u''
		try:
			enc = frame.encoding
			if enc == '':
				enc = None
		except: enc = None

		#if not message_done and enc != 'iso-8859-1' and enc != 'latin_1':
			#print "Warning: encoding should be iso-8859-1 (not",enc,") in ", song
			#message_done = True

		#print frame.fid
		#print frame.strings
		if frame.fid == 'TALB':
			try:		alb = frame.strings[0].decode(enc)
			except:
				try:	alb = unicode(frame.strings[0])
				except: alb = None
		elif frame.fid == 'TPE1':
			try:		art = frame.strings[0].decode(enc)
			except:
				try:	art = unicode(frame.strings[0])
				except: art = None

		elif frame.fid == 'TRCK':
			trk = frame.strings[0]

	return alb, art, trk


def GetArtAlb(song):
	tag_exists = False
	try:
		id3v1 = ID3v1(song)
		id3v2 = ID3v2(song)
	except IOError:
		print "IOError while reading id3 in ", song
		return None, None, None, None
	except IndexError:
		print "IndexError while reading id3 in ", song
		return None, None, None, None
	except MemoryError:
		print "MemoryError while reading id3 in ", song
		return None, None, None, None
	except UnicodeDecodeError:
		print "Error while decoding id3v2-tag", song
		return None, None, None, None
	if not id3v1.tag_exists() and not id3v2.tag_exists():
		artst 	= None
		album 	= None
		trk 	= None
		tag_exists = False
		print "no tag"
		#s = song.split('/')											#one could tag song using the folder structure
		#print "tagging", song
		##id3v1.genre  = 12
		#id3v1.artist = s[-3]
		#id3v1.album  = s[-2]
		##id3v1.title  = s[-1]
		#id3v1.commit()
	elif id3v2.tag_exists():
		tag_exists = True
		album, artst, trk = GetArtAlbv2(id3v2,song)
	elif id3v1.tag_exists():
		tag_exists = True
		album, artst, trk = GetArtAlbv1(id3v1,song)

	return artst, album, trk, tag_exists


